import axios from 'axios';
import { Store } from 'vuex';
import VueRouter from 'vue-router';
<%_ if (enableTranslation) { _%>
import TranslationService from '@/locale/translation.service';
<%_ } _%>

<%_ if (websocket === 'spring-websocket') { _%>
import TrackerService from '@/admin/tracker/tracker.service';
<%_ } _%>

export default class AccountService {

  constructor(
    private store: Store<any>,
    <%_ if (enableTranslation) { _%>
    private translationService: TranslationService,
    <%_ } _%>
    <%_ if (authenticationType === 'session' || authenticationType === 'oauth2') { _%>
    private cookie: any,
    <%_ } _%>
    <%_ if (websocket === 'spring-websocket') { _%>
    private trackerService: TrackerService,
    <%_ } _%>
    private router: VueRouter
  ) {
    this.init();
  }

  public init(): void {
    this.retrieveProfiles();
  }

  public retrieveProfiles(): Promise<boolean> {
    return new Promise(resolve => {
      axios.get('management/info').then(res => {
        if (res.data && res.data.activeProfiles) {
          this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
          this.store.commit('setActiveProfiles', res.data['activeProfiles']);
        }
        resolve(true);
      }).catch(() => resolve(false));
    });
  }

  public retrieveAccount(): Promise<boolean> {
    return new Promise(resolve => {
      axios
        .get('api/account').then((response) => {
        this.store.commit('authenticate');
        const account = response.data;
        if (account) {
          this.store.commit('authenticated', account);
          <%_ if (enableTranslation) { _%>
          if (this.store.getters.currentLanguage !== account.langKey) {
            this.store.commit('currentLanguage', account.langKey);
          }
          <%_ } _%>
          if(sessionStorage.getItem('requested-url')) {
            this.router.replace(sessionStorage.getItem("requested-url"));
            sessionStorage.removeItem("requested-url");
          }
          <%_ if (websocket === 'spring-websocket') { _%>
          this.trackerService.connect();
          <%_ } _%>
        } else {
          this.store.commit('logout');
          this.router.push('/', () => {});
          sessionStorage.removeItem("requested-url");
        }
        <%_ if (enableTranslation) { _%>
        this.translationService.refreshTranslation(this.store.getters.currentLanguage);
        <%_ } _%>
        resolve(true);
      }).catch(() => {
        this.store.commit('logout');
        resolve(false);
      });
    });
  }

  public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
    if (typeof authorities === 'string') {
      authorities = [authorities];
    }

    if (!this.authenticated || !this.userAuthorities) {
      const token = <%_ if (authenticationType === 'jwt') { _%> localStorage.getItem('<%=jhiPrefixDashed %>-authenticationToken') || sessionStorage.getItem('<%=jhiPrefixDashed %>-authenticationToken'); <%_ } else { _%> this.cookie.get('JSESSIONID') || this.cookie.get('XSRF-TOKEN'); <%_ } _%>
      if (!this.store.getters.account && !this.store.getters.logon && token) {
        return this.retrieveAccount();
      } else {
        return new Promise(resolve => { resolve(false); });;
      }
    }

    for (let i = 0; i < authorities.length; i++) {
      if (this.userAuthorities.includes(authorities[i])) {
        return new Promise(resolve => { resolve(true); });;
      }
    }

    return new Promise(resolve => { resolve(false); });;
  }

  public get authenticated(): boolean {
    return this.store.getters.authenticated;
  }

  public get userAuthorities(): any {
    return this.store.getters.account.authorities;
  }
}
